package com.fin.quant.rpc.bean;

import com.orbitz.consul.Consul;
import com.orbitz.consul.model.health.ServiceHealth;
import io.grpc.Attributes;
import io.grpc.EquivalentAddressGroup;
import io.grpc.NameResolver;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ConsulNameResolver extends NameResolver {

    private final String serviceName;

    private Consul consul;

    public ConsulNameResolver(Consul consul, String serviceName) {
        this.consul = consul;
        this.serviceName = serviceName;
    }

    @Override
    public String getServiceAuthority() {
        return serviceName;
    }

    private ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);

    @Override
    public void start(Listener listener) {
        scheduler.scheduleAtFixedRate(() -> {
            List<ServiceHealth> nodes = consul.healthClient().getHealthyServiceInstances(serviceName).getResponse();
            List<EquivalentAddressGroup> servers = new ArrayList<>();
            for (ServiceHealth service : nodes) {
                InetSocketAddress address = new InetSocketAddress(service.getService().getAddress(), service.getService().getPort());
                servers.add(new EquivalentAddressGroup(address));
            }
            listener.onAddresses(servers, Attributes.EMPTY);
        }, 0, 10, TimeUnit.SECONDS);
    }

    @Override
    public void shutdown() {
        // 清理资源
        consul.destroy();
    }
}
